﻿using System;
using System.Collections.Generic;
using System.Linq;
using CML.Intercamber.Business.Model;
using MvcJqGrid;

namespace CML.Intercamber.Business.Dao
{
    public class UserInvitesDao
    {
        public static void Insert(UserInvite val)
        {
            using (var context = new IntercamberEntities())
            {
                context.UserInvite.Add(val);
                context.SaveChanges();
            }
        }

        public static UserInvite FindInvites(Guid id)
        {
            UserInvite res = null;
            using (var context = new IntercamberEntities())
            {
                res = context.UserInvite.FirstOrDefault(x => x.InviteId == id);
            }
            return res;
        }

        public static
            GridData<UserInviteDetail> ListUserInvites(GridSettings gridSettings, long idUserCreate)
        {
            List<UserInviteDetail> res;
            int totalRecords;
            int totalPages = 0;

            using (var context = new IntercamberEntities())
            {
                var req = context.UserInvite
                            .Where(x => x.IdUserCreation == idUserCreate)
                            .Select(x => new UserInviteDetail
                            {
                                AccountCreated = x.AccountCreated, 
                                DateCreation = x.DateCreation, 
                                Email = x.Email,
                                EmailSent = x.EmailSent, 
                                IdEstablishment = x.IdEstablishment, 
                                IdUserCreation = x.IdUserCreation, 
                                IdUserInvite = x.IdUserInvite, 
                                InviteId = x.InviteId, 
                                LearnLanguage = x.LearnLanguage, 
                                IdUser = context.Users.Where(u => u.Email == x.Email).Select(u => u.IdUser).FirstOrDefault()
                            })
                            .OrderByDescending(x => x.DateCreation);

                totalRecords = req.Count();
                if (gridSettings.PageSize > 0)
                    totalPages = (int)Math.Ceiling((decimal)totalRecords / gridSettings.PageSize);
                res = req
                       .Skip(gridSettings.PageSize * (gridSettings.PageIndex - 1))
                       .Take(gridSettings.PageSize)
                       .ToList();
            }
            return new GridData<UserInviteDetail>
            {
                page = gridSettings.PageIndex, // number of requested page
                records = totalRecords, // total records from query 
                total = totalPages, // total pages of query 
                rows = res
            };
        }
    }
}
